package com.objectdraw.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import com.objectdraw.server.commands.Command;
import com.objectdraw.server.data.RequestData;
import com.objectdraw.server.data.ResponseData;

/**
 * The purpose of this class is to take a request from the client, wrap it in an
 * object the request processors can understand and then pass that request to the
 * correct processor
 * 
 * @author Harrison
 */
public class ObjectDrawHandler extends Thread {

	private Socket client = null;
	private String clientName = "";

	public ObjectDrawHandler(Socket client) {
		this.client = client;
	}

	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(client
					.getInputStream()));
			while (!client.isClosed()) {// && in.ready()
				try {
					if (true) {
						String requestString = in.readLine();
						if (requestString != null) {
							RequestData req = new RequestData();
							req.setClient(client);
							req.setCommand(requestString.substring(0, requestString.indexOf(" ")));
							if("connect".equalsIgnoreCase(req.getCommand()))
							{	
								req.setParams(requestString.substring(requestString.indexOf(" ") + 1));
								clientName = req.getParams();
							}else{
								req.setParams(requestString.substring(requestString.indexOf(" ") + 1) + " " +clientName);
							}
							Command cmd = ObjectDrawServer.getCommandHandlers();
							
							ObjectDrawServer.getInstance().resetIdleTime();

							cmd.processRequest(req, new ResponseData());
						}
					}
				} catch (Exception e) {
					System.err.println("client handler almost died");
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
